package com.liaoyifan.core.opera;

import com.liaoyifan.core.enums.CoreEnum;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

@SuppressWarnings({"unchecked", "unused"})
public class CoreEnumTypeHandler<E extends CoreEnum<T>, T extends Serializable>
        extends BaseTypeHandler<E> {

    private final Class<E> type;

    public CoreEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setObject(i, parameter.getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getEnumByValue((T) rs.getObject(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getEnumByValue((T) rs.getObject(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getEnumByValue((T) cs.getObject(columnIndex));
    }

    private E getEnumByValue(T value) {
        if (value == null) {
            return null;
        }
        for (E enumConstant : type.getEnumConstants()) {
            if (value.equals(enumConstant.getValue())) {
                return enumConstant;
            }
        }
        throw new IllegalArgumentException(
                "No enum constant " + type.getName() + " with value " + value);
    }
}
